from django.shortcuts import render,redirect
from django.views import View
from .forms import *
from django.http import HttpResponse,JsonResponse
from utils.code import gene_code
from utils.loadaddr import *
from cart.cartmanager import SessionCartManager
# Create your views here.
class FormTestView(View):
    def get(self,request):
        #生成表单类的对象
        u_form = RegisterForm()
        return render(request,'form.html',{'u_form':u_form})
    def post(self,request):
        #用提交的表单数据生成表单类对象
        u_form  = RegisterForm(request.POST)
        #表单类对象进行数据验证
        if u_form.is_valid():   #验证成功
            return HttpResponse('提交成功')
        else:      #验证失败
            #将错误信息拼接成一个字符串 u_form.errors 存放错误信息，是一个字典
            str = ''
            for key,value in u_form.errors.items():
                str = str+key+'=='+value+'<br>'
            return HttpResponse(str)


class RegisterView(View):
    def get(self,request):
        return render(request, 'register.html')

    def post(self,request):
        #首先获取提交的表单中的数据
        datas = request.POST.dict()
        #创建一个表单类对象
        register_form = RegisterForm(datas)
        #进行表单验证
        if register_form.is_valid():
            #创建一个新用户
            user = User.register(**register_form.cleaned_data)
            #在session保存用户信息
            request.session['user'] = user
            # 跳转到用户中心
            return redirect('/user/usercenter')
        else:
            return render(request,'register.html',{'info':datas,'errors':register_form.errors})


class UserCenterView(View):
    def get(self,request):
        user = request.session.get('user')
        return render(request,'usercenter.html',{'user':user})


class LoginView(View):
    def get(self, request):
        #获取其它页面跳转时传递的参数
        redirect = request.GET.get('redirect')
        cartitems = request.GET.get('cartitems')
        return render(request,'login.html',{'redirect':redirect,'cartitems':cartitems})

    def post(self,request):
        try:
            #判断用户是否登录成功
            user = User.login(**request.POST.dict())
            #登录成功将用户保存到session中
            request.session['user'] = user
            #将未登录时存储在session中的购物车存储到数据库
            SessionCartManager(request.session).migrateSession2DB()
            #如果登录页面是从其它页面跳转过来的，还要跳转回去
            redir = request.POST.get('redirect')
            if redir == 'cart':
                return redirect('/cart/cart.html')
            elif redir == 'order':
                return redirect('/order/?cartitems='+request.POST.get('cartitems'))
            #跳转到用户中心
            return redirect('/user/usercenter')
        except UserNotExistException:
            return render(request,'login.html')


class CodeView(View):
    def get(self,request):
        #生成台验证码
        img,code = gene_code()
        #将code保存到session中，后边会和用户输入的验证码进行比对
        request.session['code'] = code
        #将图片创建成响应对象发送给客户端
        return  HttpResponse(img,content_type='image/png')


class CheckCodeView(View):
    def get(self,request):
        #获取传过来的验证码
        code = request.GET.get('code',None)
        #从session中获取前面保存的验证码
        scode =  request.session.get('code','-1')
        #进行比对
        result = (code == scode)
        #返回json的响应
        return JsonResponse({'checkFlag':result})


class LogoutView(View):
    def post(self,request):
        #判断用户是否登录,如果已登录，删除session中保存的登录信息
        if 'user' in request.session:
            del request.session['user']

        return JsonResponse({'result':True})


class AddressView(View):
    def get(self,request):
        provinces = get_provinces()
        user = request.session.get('user')
        addresses = []
        for address1 in Address.objects.filter(user=user):
            name = address1.uname
            phone = address1.phone
            address, details = (lambda a: (''.join(a[:-1]), ''.join(a[-1])))(address1.address.split(','))
            addresses.append({'name': name, 'phone': phone, 'address': address, 'details': details})
        return render(request, 'address.html', {"provinces": provinces, "addresses": addresses})
    def post(self,request):
        type = request.POST.get('type')
        if type == '1':   #根据省的id去获取所有的市和第一个市的所有的区
            provId = request.POST.get('provinceId')
            citys,areas = get_citys_areas_by_provinceid(provId)
            return JsonResponse({'citys':citys,'areas':areas})
        elif type == '2':    #根据市的id去获取所有的区
            cityId = request.POST.get('cityId')
            areas = get_areas_by_cityid(cityId)
            return JsonResponse({'areas':areas})
        elif type == '3':    #保存地址
            #1、接收数据并保存地址
            address = request.POST.get('address')
            name = request.POST.get('name')
            phone = request.POST.get('phone')
            user = request.session.get('user')
            #保存地址
            if user.address_set.count() == 0:
                isdefault = True
            else:
                isdefault = False
            Address.objects.create(uname=name,phone=phone,address=address,user=user,isdefault=isdefault)
            #2、将当前用户的所有的收货地址传送给客户端
            html = '''<div class='dizhi'><p>姓名：{name}</p><p>手机号：{phone}</p><p>省市：{address}</p><p>详细地址：{details}</p></div>'''
            addresses = []
            for add in user.address_set.all():
                name = add.uname
                phone = add.phone
                list = add.address.split(',')
                address = ''.join(list[:-1])
                details = list[-1]
                addresses.append(html.format(name=name,phone=phone,address=address,details=details))
            return JsonResponse({'addresses':addresses})
